package com.mljr.example.http;


import com.ctakit.sdk.app.base.MyActivity;
import com.ctakit.sdk.exception.BusinessException;
import com.mljr.example.base.BaseUtil;

public class HttpManager {
    private IHttpResult httpResult;
    private MyActivity myActivity;
    private boolean showProgressDialog = true;

    public HttpManager(final MyActivity myActivity, IHttpResult httpResult) {
        this.httpResult = httpResult;
        this.myActivity = myActivity;
    }

    public HttpManager(boolean showProgressDialog, final MyActivity myActivity, IHttpResult httpResult) {
        this.httpResult = httpResult;
        this.myActivity = myActivity;
        this.showProgressDialog = showProgressDialog;
    }

    public void execute() {
        execute("");
    }

    public void execute(String tip) {
        if (showProgressDialog) {
            myActivity.showProgressDialog(tip);
        }

        MyHttpTask<String, BusinessException, Boolean> task = new MyHttpTask<String, BusinessException, Boolean>() {

            @Override
            protected Boolean doInBackground(String... params) {
                boolean result = false;
                try {
                    httpResult.doRequest();
                    result = true;
                } catch (BusinessException e) {
                    publishProgress(e);
                }
                return result;
            }

            @Override
            protected void onProgressUpdate(BusinessException... ex) {

                if (myActivity == null) {
                    return;
                }

                if (myActivity.getActivity() == null) {
                    return;
                }
                //myActivity.cancelProgressDialog();

                if (!BaseUtil.checkBussinssExcetion(myActivity, ex)) {
                    if (!httpResult.failed(ex)) {
                        myActivity.showToastMsg(ex[0].getMessage());
                    }
                }
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (myActivity == null) {
                    return;
                }
                if (myActivity.getActivity() == null) {
                    return;
                }
                myActivity.cancelProgressDialog();
                if (result) {
                    httpResult.success();
                }

            }

        };
        task.execute();
    }

}
